#ifndef TIMERSERVICE_H
#define TIMERSERVICE_H

#include "../global.h"
#include "timerfactory.h"
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/function.hpp>
#include <boost/asio/detail/config.hpp>

class Timer;
class AsyncService;

class TimerService : protected boost::noncopyable
{
public:
    typedef boost::mutex Mutex;
    typedef boost::shared_ptr< Timer > TimerPtr;
    typedef boost::unordered_map< unsigned int, TimerPtr > TimerMap;
    typedef boost::shared_ptr< TimerMap > TimerMapPtr;
    typedef boost::unordered_map< unsigned int, TimerMapPtr > OwnerMap;
    typedef boost::unordered_set< TimerPtr > TrashSet;

    typedef boost::function< void (unsigned int, unsigned int) > Notifier;

public:
    TimerService(AsyncService &service);
    ~TimerService();

    int  setTimer(unsigned int owner,
                  unsigned int id,
                  unsigned long elapse,
                  unsigned int repeat,
                  BOOST_ASIO_MOVE_ARG(Notifier) n);

    void killTimer(unsigned int owner, unsigned int id);

protected:
    void onTimeout(Notifier n, TimerPtr timer, int err);
    void onTrash();

protected:
    AsyncService &m_service;

    TimerFactory m_timerFactory;

    OwnerMap m_timers;

    TrashSet m_trashs;

    Mutex m_timerLock;

    Mutex m_trashLock;
};

#endif // TIMERSERVICE_H
